//
//  KeychainHelper.swift
//  Kosspot
//
//  Created by 胡辉 on 2025/6/24.
//

import Security
import Foundation

struct KeychainHelper {
    static func saveToken(_ token: String) {
        let data = Data(token.utf8)
        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrAccount as String: "authToken",
            kSecAttrService as String: "com.Kosspot.Kosspot",
            kSecValueData as String: data
        ]
        SecItemDelete(query as CFDictionary)
        SecItemAdd(query as CFDictionary, nil)
    }
    
    static func getToken() -> String? {
        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrAccount as String: "authToken",
            kSecAttrService as String: "com.Kosspot.Kosspot",
            kSecReturnData as String: true,
            kSecMatchLimit as String: kSecMatchLimitOne
        ]
        
        var data: AnyObject?
        SecItemCopyMatching(query as CFDictionary, &data)
        guard let tokenData = data as? Data else { return nil }
        
        return String(data: tokenData, encoding: .utf8)
    }
    
    static func deleteToken() {
        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrAccount as String: "authToken",
            kSecAttrService as String: "com.Kosspot.Kosspot",
        ]
        SecItemDelete(query as CFDictionary)
    }
}
